
using System.Collections.Generic;
using UnityEngine;



public class ObjectPool:MonoBehaviour{



    //对象池名称
    public string poolName;
    //预制体
    public GameObject prefab;

    //初始化大小
    public int initNum;

    public List<GameObject> list;



    //初始化对象池
    public void initPool()
    {


        for (int i = 0; i < initNum; i++)
        {
             GameObject gmpre= Instantiate(prefab);
            gmpre.transform.parent = gameObject.transform;
            gmpre.name = poolName + "(" + "i" + ")";
            gmpre.SetActive(false);
            list.Add(gmpre);
        }

    }






    //取出当前列表中可以的对象  不存在就新建一个然后返回
    public GameObject availableObject()
    {

        GameObject availableObject = new GameObject();

        foreach (GameObject gm in list)
        {
            if (!gm.active)
            {
                availableObject = gm;
            }

        }


        if (availableObject == null)
        {
            //不存在就生成一个
            availableObject= Instantiate(prefab);
            availableObject.transform.parent = gameObject.transform;
            availableObject.SetActive(false);
            list.Add(availableObject);
        }


        return availableObject;
    }





    //生成一个对象
    public GameObject preparObject()
    {


        GameObject availableObject = this.availableObject();

        availableObject.SetActive(true);
        return availableObject;

    }




    //删除指定的元素
    public void deleteObject(GameObject gm)
    {

        for (int i = 0; i < list.Count; i++)
        {
            if (list[i] == gm)
            {

                gm.SetActive(false);

            }


        }
    }

    //清空整个对象池
    public void deleteAllObject()
    {

        for (int i = 0; i < list.Count; i++)
        {
            list[i].SetActive(false);
        }
    }



    public List<GameObject> getAllSavePool() {


        List<GameObject> gmlist = new List<GameObject>();

        for (int i = 0; i < list.Count; i++)
        {
            if (list[i].activeSelf) {
                gmlist.Add(list[i]);



            }
        }


        return gmlist;
    }



}


